/*
 * @Description:webpack配置
 * @Author: r_yuesheng
 * @Date: 2021-07-08 15:01:48
 * @LastEditTime: 2022-04-09 15:27:05
 * @LastEditors: r_yuesheng
 */
const { when, whenDev, whenProd } = require('@craco/craco');
const CracoLessPlugin = require('craco-less');
const path = require('path');
const compressionWebpackPlugin = require('compression-webpack-plugin');
const AntdDayjsWebpackPlugin = require('antd-dayjs-webpack-plugin');
const FastRefreshCracoPlugin = require('craco-fast-refresh');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const Autoprefixer = require('autoprefixer');
const pathResolve = pathUrl => path.join(__dirname, pathUrl);
const WebpackBar = require('webpackbar');
const TimeStamp = new Date().getTime();
const isDev = process.env.NODE_ENV === 'development';
console.log('我是环境：', isDev);
module.exports = {
  webpack: {
    // devtool: 'none',
    alias: {
      '@': pathResolve('src')
    },
    plugins: [
      // webpack构建进度条
      new WebpackBar({
        basic: false,
        profile: true
      }),
      // 时间转换工具采取day替换moment
      new AntdDayjsWebpackPlugin(),
      //配置gzip
      new compressionWebpackPlugin({
        filename: '[path].gz[query]',
        algorithm: 'gzip',
        test: /\.js$|\.json$|\.css/,
        threshold: 10240, // 只有大小大于该值的资源会被处理
        minRatio: 0.8 // 只有压缩率小于这个值的资源才会被处理
        // deleteOriginalAssets: true // 删除原文件
      })
    ],
    rules: [
      {
        test: /\.(css|less)$/,
        use: [
          isDev
            ? {
                loader: 'style-loader',
                options: {
                  sourceMap: isDev
                }
              }
            : MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
            options: {
              importLoaders: 1,
              sourceMap: isDev
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              ident: 'postcss',
              sourceMap: isDev ? 'inline' : false,
              plugins: [Autoprefixer()]
            }
          },
          {
            loader: 'less-loader',
            options: {
              sourceMap: isDev
            }
          }
        ]
      }
    ],
    //抽离公用模块
    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
            chunks: 'initial',
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0
          },
          vendor: {
            test: /node_modules/,
            chunks: 'initial',
            name: 'vendor',
            priority: 10,
            enforce: true
          }
        }
      }
    },
    configure: (webpackConfig, { env, paths }) => {
      paths.appBuild = 'dist'; // 输出的打包目录
      webpackConfig.devtool = 'none'; //是否输出源文件 source-map
      /**
       * 修改 output
       */
      webpackConfig.output = {
        ...webpackConfig.output,
        path: pathResolve('dist'),
        publicPath: '/',
        filename: `static/js/[name]_${TimeStamp}.js`,
        chunkFilename: `static/js/[name]_${TimeStamp}.js`
      };
      // 返回重写后的新配置
      return webpackConfig;
    }
  },
  devServer: {
    port: 7017,
    open: true
    // proxy: {
    //   '/api': {
    //     target: 'https://placeholder.com/',
    //     changeOrigin: true,
    //     secure: false,
    //     xfwd: false,
    //   }
    // }
  },
  babel: {
    plugins: [
      ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }],
      ['@babel/plugin-proposal-decorators', { legacy: true }]
    ]
  },
  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        // 此处根据 less-loader 版本的不同会有不同的配置，详见 less-loader 官方文档
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: {},
            javascriptEnabled: true
          }
        }
      }
    },
    // {
    //   plugin: StyleResourcesLoader,
    //   options: {
    //     'style-resources-loader': {
    //       preProcessor: 'less',
    //       patterns: [
    //         // 全局变量路径，不能使用路径别名
    //         path.resolve(__dirname, './src/styles/variables.less')
    //       ]
    //     }
    //   }
    // },
    // {
    //   plugin: CracoAntDesignPlugin,
    //   options: {
    //     customizeThemeLessPath: path.join(__dirname, './src/styles/variables.less')
    //   }
    // },
    // 热更新
    ...whenDev(
      () => [
        {
          plugin: FastRefreshCracoPlugin
        },
        {
          plugin: new AntdDayjsWebpackPlugin()
        }
      ],
      []
    )
  ]
};
